<?php

namespace app\admin\controller;

use think\Controller;

use  app\admin\model\User as UserModel;
use think\Request;
use think\Db;

class User extends Controller
{

    /**
     * 显示管理员列表页.
     *
     * @return \think\Response
     */
    public function index()
    {
        $user=new UserModel();
        $data=$user->getALL();
//        dump($data);
        return view('admin/index',[
            'title'=>'用户列表',
            'data'=>$data
        ]);

    }


    /*
     * 显示新增管理员表单页
     *
     *
     * */
    public function add()
    {
        return view('admin/add',['title'=>'新增管理员']);
    }



    /*
     * 处理新增管理员表单页
     *
     *
     * */
    public  function save(Request $request)
    {
       $p=$request->post();

        $user=new UserModel();
        $result=$user->save($p);
        dump($result);
        if ($result>0) {
            return $this->success('添加成功', url('admin/user/index'));
        } else {
            return $this->error('添加失败,请重试!!');
        }

    }


    /**
     * 加载编辑用户界面
     * @param uid
     *
     * @return \think\Response
     */
    public function  edit($id)
    {
        $result= Db::table('hb_auser')->where('id',$id)->find();

        return $result;
    }


    public function  doedit(Request $request)
    {
        $p=$request->post();
//        dump($p);
        $result=  Db::table('hb_auser')->where('id', $p['id'])->update(['username' => $p['username']]);
        return  $p;
    }

    /**
     * 删除用户
     * @param uid
     *
     * @return \think\Response
     */
    public function del($id)
    {


        $a= Db::table('hb_auser')->where('id',$id)->delete();

        $b= Db::table('user_role')->where('u_id',$id)->delete();

        if ($a && $b){
           return $id;
        }
    }

    /**
     * 加载分配角色
     *
     */
    public function assignRoles($id)
    {
        $all = db('role')
            ->select();
//        return array('data' => $all);

        $result = Db::table(['hb_auser' => 'u', 'user_role' => 'ur'])
            ->field('ur.r_id')
            ->where('u.id=ur.u_id')
            ->where('u.id',$id)
            ->select();
        return json(["all"=>$all,"result"=>$result,"uid"=>$id]);
    }


    /**
     * 处理分配角色
     *
     */
    public function saveRole(Request $request)
    {
        $p=$request->post();

        $uid=$p['id'];
        $rid=json_decode($p['role']);

        foreach ($rid as $v)
        {
            $data[]=['u_id'=>$uid,'r_id'=>$v];
        }
        Db::table('user_role')
            ->where('u_id',$uid)
            ->delete();

        Db::table('user_role')->insertAll($data);

        $roles = Db::table(['hb_role' => 'r', 'user_role' => 'ur'])
            ->field(['r.rolename'])
            ->where('r.id=ur.r_id')
            ->where('ur.u_id', $uid)
            ->select();


        foreach ($roles as $v){
            $arr[]=$v['rolename'];
        }

        $str=implode(' ',$arr);

        return $str;





    }

}

